
global.Promise = require('bluebird')
global.Request = Promise.promisifyAll(require('request'))
global.config = require('./config')
global.Cache = require('./cache')
global.moment = require('moment')
const {get_quotations, get_best_price} = require('./market')
const maxTradeInteval = config.timeout  // how long to generator the order to make a trade
const {cancelBadOrders, generate_depth, generate_trade, getbtcprice, getContractInfo} = require('./tools')

global.LOG = (msg) => {
    console.log(...msg)
}


let latest_ask = 0, latest_market = '', trade_time_last = moment().add(-2, 'days').valueOf()
async function main (base = process.argv[2], quote = process.argv[3]) {
    if (!base) {
        LOG([`base is ${base}, must be a lower case coin name`])
        return
    }

    if (!quote) {
        LOG([`quote is ${quote}, auto will be usdt`])
        quote = 'usdt'
    }
    LOG([base, quote])

    if (base === 'loom') {
        quote = 'btc'
    }
    try {
        await getContractInfo()
        config.btc_price = await getbtcprice()
        if (config.btc_price === 0) {
            await Promise.delay(maxTradeInteval)
            main(base, quote)
        }
        const market_prices = await get_quotations(base, quote)

        const priceValidPercent = 0.05 //当前价格和上一价格价差不超过5%视为有效价格
        const [best_market, useful_market] = await get_best_price(market_prices, latest_market, priceValidPercent, latest_ask)
        LOG([new Date(), best_market, useful_market])
        let best_ask_price = 0
        let best_bid_price = 0

        if (best_market && useful_market[best_market]) {
        	best_ask_price = useful_market[best_market][0]
        	best_bid_price = useful_market[best_market][1]
        	latest_market = best_market
        	latest_ask = best_ask_price

            if (base === 'loom') {
                best_ask_price *= config.btc_price
                best_bid_price *= config.btc_price
                console.log('loom', best_ask_price, best_bid_price)
                quote = 'usdt'
            }
        } 

        if ( best_ask_price > 0.00000001 && best_bid_price > 0.00000001 ) {
        	
        	await cancelBadOrders({base, quote, best_ask_price, best_bid_price})
            const depthMinBuy = config.contractMap[base][2] / best_bid_price
            const depthMinSell = config.contractMap[base][2] / best_ask_price 
            await generate_depth({base, quote, best_ask_price, best_bid_price, depthMinBuy, depthMinSell})
        	trade_time_last = await generate_trade({base, quote, best_ask_price, best_bid_price, trade_time_last})
        }
    } catch (error) {
       LOG(['main: ', error.code || error.message || error]) 
    }
    await Promise.delay(maxTradeInteval)
    main(base, quote)
}

main()